import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, ActionSheetController, AlertController, ViewController, Navbar } from 'ionic-angular';
import { TeachSignPage } from "../teach-sign/teach-sign";
import { UnitListPage } from "../unit-list/unit-list";
import { BarragePage } from "../barrage/barrage";
import { TeacheraddClassPage } from "../teacheradd-class/teacheradd-class";
import { RandomCallPage } from "../random-call/random-call";
import { UnitSourceListPage } from "../unit-source-list/unit-source-list";
import { MainPage } from "../main/main";
import { StudentAddPage } from "../student-add/student-add";




import { ApiProvider } from "../../providers/api/api";

import { Injectable } from '@angular/core';

import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/retry';
import { observable } from "rxjs/symbol/observable";
import { UpgradeAppProvider } from "../../providers/upgrade-app/upgrade-app";


/**
 * Generated class for the TeachingPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-teaching',
  templateUrl: 'teaching.html',
})
export class TeachingPage {
  @ViewChild(Navbar) navBar: Navbar;
  constructor(public navCtrl: NavController, public navParams: NavParams, private wsService: UpgradeAppProvider, private toastCtrl: ToastController, public http: ApiProvider) {
  }
  courseclassid;//'课程id';
  staname;//'开始课程';
  courseName;//课程名称
  classCourseId;//班课id
  unitId;//单元id
  classcourse_num;//班课授课码
  teacherId;
  sta;//判断授课还是继续授课
  teaching_status = "开始授课";
  is_s;
  data_s;
  poptime = false;//时间判定弹出
  ptime;//websocket获取的时间
  stime;
  dtime;
  myDate;
  StartDate = "";
  studentsta = false;//判断新增是否可以跳转

  signstat = "开始签到";//开始签到判断

  ngOnInit() {

  }

  backButtonClick = (e: UIEvent) => {

    this.navCtrl.push(MainPage);

  };

  //是否可以点击开始授课提示
  presentToast() {
    let toast = this.toastCtrl.create({
      message: '请先开始授课',
      duration: 3000,//3秒后自动消失
      position: 'bottom'//位置
    });

    toast.present();//符合触发条件后立即执行显示。一定不能忘了这个
  }

  //是否可以点击新增学生提示
  presentToaststudent() {
    let toast = this.toastCtrl.create({
      message: '没有新增',
      duration: 3000,//3秒后自动消失
      position: 'bottom'//位置
    });

    toast.present();//符合触发条件后立即执行显示。一定不能忘了这个
  }


  presentsign() {
    let toast = this.toastCtrl.create({
      message: '请先开始授课',
      duration: 3000,//3秒后自动消失
      position: 'bottom'//位置
    });

    toast.present();//符合触发条件后立即执行显示。一定不能忘了这个
  }

  ngAfterViewInit() {



    //发送websocket消息
    this.wsService.createObservableSocket(`${this.http.sendwsinfo}/FourInOneTeacherMgt/websocket`)//ws://192.168.0.28:8080/FourInOneTeacherMgt/websocket
      .subscribe(
        data => console.log("25" + data),
        err => console.log(err),
        () => console.log('l it s over')
      )
    //接受websoket消息
    this.wsService.creatsocket(`${this.http.receiveserve}/FourInOneTeacherAppServer/websocket`)//ws://192.168.0.35:8081/FourInOneTeacherAppServer/websocket
      .subscribe(
        data => this.data_sta(data),
        err => console.log(err),
        () => console.log('it s over')
      )
    //websoket判断新增学生是否可以点击
    this.wsService.creatsocketstudent(`${this.http.receivews}/FourInOneAppServer/websocketJoinCourse`)//ws://192.168.0.28:8080/FourInOneAppServer/websocketJoinCourse
      .subscribe(
        data => this.data_student(data),
        err => console.log(err),
        () => console.log('it s over')
      )


    this.navBar.backButtonClick
      = this.backButtonClick;
  }


  //websoket判断是否可以点击新增学生

  data_student(a) {
    console.log(963)
    console.log(a)
    if (a == "NewStudent") {
      this.studentsta = true;
    }
  }
  changeDate(a) {
    this.stime = a.replace('T', " ");
    this.dtime = this.stime.slice(0, 16);
    this.ptime = this.dtime;
  }
  // data_time(a) {
  //   console.log(123);
  //   console.log(a);
  //   if(a.split(',')[3]!="undefind"){
  //     this.ptime = this.ptime = a.split(',')[3]
  //   }


  // }
  //根据websocket操作
  data_sta(a) {
    console.log(989);
    console.log(a);
    if (a.split(',')[0] == "updateStartCourseState") {
      if (a.split(',')[4] == 0) {
        this.teaching_status = "结束授课";
      }
      if (a.split(',')[4] == 1) {
        this.navCtrl.push(MainPage)
      }
    }

    if (a.split(',')[0] == "deadLine") {
      if (a.split(',')[4]) {
        this.ptime = a.split(',')[4]
      }
    }
  }

  //点击时间确认按钮执行操作
  maketime() {
    //this.ptime要传走
    this.poptime = false;
    this.sksta();
    this.qdsta();
    this.upendclasstime(this.ptime);
    this.navCtrl.push(MainPage)



  }
  sendMessageToServer() {

    var stat;
    if (this.teaching_status == "结束授课") {
      stat = 1;
      // this.teaching_status = "开始授课";
      this.poptime = true;
      console.log(14);
      console.log(`${this.classCourseId},${this.unitId},${stat}`);
      this.wsService.sendMessage(`updateStartCourseState,${this.classCourseId},${this.unitId},${stat}`);



    } else if (this.teaching_status == "开始授课") {
      //   this.teaching_status == "结束授课"
      stat = 0;
      console.log(789)
      console.log(`updateStartCourseState,${this.classCourseId},${this.unitId},${stat}`)
      this.wsService.sendMessage(`updateStartCourseState,${this.classCourseId},${this.unitId},${stat}`);

    }




  }


  ionViewDidLoad() {


    this.teacherId = localStorage.getItem('teacherId');

    this.sta = this.navParams.get("sta");
    this.is_s = this.navParams.get("is_s");
    this.courseName = this.navParams.get("className");
    this.courseName = this.navParams.get("courseName");


    // this.courseclassid = this.navParams.get("courseclassid");




    this.classcourse_num = localStorage.getItem('classcourse_num');
    this.unitId = localStorage.getItem('unitId');
    this.classCourseId = localStorage.getItem('classCourseId');



    // this.teachingstatus(this.sta, this.is_s);

    //请求接口判断新增学生是否可以点击
    console.log(222222)
    console.log(`${this.teacherId},${this.classCourseId}`)
    this.http.post("/teacherStudentController/getTeaStudentList2.do", { teacherId: this.teacherId, page: 1, rows: 5, classCourseId: this.classCourseId, applyState: 0 }).subscribe(item => {
      console.log(333)

      console.log(item)
      if (item['rows'].length > 0) {

        this.studentsta = true;
      }

    })




    this.sksta();
    this.qdsta();



  }

  upendclasstime(time) {
    this.http.post("/unitTeacherController/updateDeadLineTimeOfTeacher.do", { courseclassid: this.classCourseId, unit_id: this.unitId, deadLineTime: time }).subscribe(item => {
      console.log(258)
      console.log(item)
      if (item["result"] != 1) {
        console.log("结束课程时间设置失败")
      }
    })
  }

  qdsta() {
    this.http.post("/startCourseTeacherController/getSignOfTeacher.do", { userId: this.teacherId, unitId: this.unitId }).subscribe(item => {
      if (item["status"] == 0) {
        this.signstat = "开始签到";
      } else {
        this.signstat = "结束签到";
      }
    })
  }
  sksta() {
    console.log(123)
    console.log(this.classCourseId,this.unitId)
    this.http.post("/courseTeacherController/getStartCourseOfTeacher.do", { classcourseid: this.classCourseId, unitid: this.unitId }).subscribe(item => {
      console.log(12)
      console.log(item)

      //0开启
      if (item["result"] == 0) {
        this.teaching_status = "结束授课"
      } else if (item["result"] == 1) {
        this.teaching_status = "开始授课"
      }


    })
  }

  // teachingstatus(s, i) {
  //   if (s == "hot" && i == 0) {
  //     this.teaching_status = "结束授课"
  //   } else {
  //     this.teaching_status = "开始授课"
  //   }
  // }
  sign() {
    if (this.teaching_status == "结束授课" && this.signstat == "开始签到") {
      this.navCtrl.push(TeachSignPage, { classCourseId: this.classCourseId, unitId: this.unitId, skysta: 2 });
    } else if (this.teaching_status == "结束授课" && this.signstat == "结束签到") {
      this.navCtrl.push(TeachSignPage, { classCourseId: this.classCourseId, unitId: this.unitId, skysta: 1 });
    } else {
      this.presentsign();
    }

  }
  UnitList() {
    this.navCtrl.push(UnitListPage, { classCourseId: this.classCourseId, teacherId: this.teacherId, courseName: this.courseName })
  }
  barrage() {
    if (this.teaching_status == "结束授课") {
      this.navCtrl.push(BarragePage, { courseclassid: this.classCourseId, unitId: this.unitId, teacherId: this.teacherId })
    } else {
      this.presentToast();
    }

  }
  teacheradd() {
    this.navCtrl.push(TeacheraddClassPage, { classcourseId: this.classCourseId, classcourseNum: this.classcourse_num, unitId: this.unitId, teacherId: this.teacherId });
  }
  randomcall() {
    this.wsService.sendMessage(`openQuestion,${this.classCourseId},${this.unitId}`);
    this.navCtrl.push(RandomCallPage, { courseclassid: this.classCourseId, unitId: this.unitId });
  }

  studentadd() {
    if (this.studentsta) {
      this.navCtrl.push(StudentAddPage, { unitId: this.unitId, classcourseId: this.classCourseId });
    } else {
      this.presentToaststudent();
    }

  }

  /**
   * 跳转至单元下的资源习题列表
   * @param unitId
   */
  showSource(unitId) {
    localStorage.setItem("class_type", "60001");

    this.navCtrl.push(UnitSourceListPage, {
      classCourseId: this.classCourseId, teacherId: this.teacherId, unitId: this.unitId, studentId: this.teacherId,
      classType: "60001", sourceType: 'xt'
    });
  }

}
